import os
import threading
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
import paramiko
from paramiko import SFTPServer, SFTPServerInterface, SFTPAttributes
from socketserver import ThreadingTCPServer

# FTP 服务器配置
FTP_HOST = "0.0.0.0"
FTP_PORT = 21
FTP_USER = "user"
FTP_PASSWORD = "password"
FTP_DIRECTORY = os.path.join(os.getcwd(), "ftp_files")

# SFTP 服务器配置
SFTP_HOST = "0.0.0.0"
SFTP_PORT = 2222
SFTP_USER = "user"
SFTP_PASSWORD = "password"
SFTP_DIRECTORY = os.path.join(os.getcwd(), "sftp_files")

# 确保目录存在
os.makedirs(FTP_DIRECTORY, exist_ok=True)
os.makedirs(SFTP_DIRECTORY, exist_ok=True)

# FTP 服务器实现
def start_ftp_server():
    authorizer = DummyAuthorizer()
    authorizer.add_user(FTP_USER, FTP_PASSWORD, FTP_DIRECTORY, perm="elradfmw")  # 权限：读写等

    handler = FTPHandler
    handler.authorizer = authorizer

    server = FTPServer((FTP_HOST, FTP_PORT), handler)
    print(f"FTP 服务器已启动，地址：{FTP_HOST}:{FTP_PORT}")
    server.serve_forever()

# SFTP 服务器实现
class MySFTPServerInterface(SFTPServerInterface):
    def __init__(self, server, *args, **kwargs):
        super().__init__(server, *args, **kwargs)
        self.root = SFTP_DIRECTORY

    def list_folder(self, path):
        real_path = os.path.join(self.root, path.lstrip("/"))
        for filename in os.listdir(real_path):
            file_path = os.path.join(real_path, filename)
            attr = SFTPAttributes.from_stat(os.stat(file_path))
            attr.filename = filename
            yield attr

    def open(self, path, flags, attr):
        real_path = os.path.join(self.root, path.lstrip("/"))
        return open(real_path, flags)

def start_sftp_server():
    host_key = paramiko.RSAKey.generate(2048)
    transport = paramiko.Transport((SFTP_HOST, SFTP_PORT))
    transport.add_server_key(host_key)

    class MySFTPServer(paramiko.ServerInterface):
        def check_auth_password(self, username, password):
            if username == SFTP_USER and password == SFTP_PASSWORD:
                return paramiko.AUTH_SUCCESSFUL
            return paramiko.AUTH_FAILED

    transport.start_server(server=MySFTPServer())
    print(f"SFTP 服务器已启动，地址：{SFTP_HOST}:{SFTP_PORT}")

    while True:
        channel = transport.accept()
        if channel is None:
            continue
        server = SFTPServer(channel, MySFTPServerInterface)

# 启动 FTP 和 SFTP 服务器
if __name__ == "__main__":
    ftp_thread = threading.Thread(target=start_ftp_server, daemon=True)
    sftp_thread = threading.Thread(target=start_sftp_server, daemon=True)

    ftp_thread.start()
    sftp_thread.start()

    ftp_thread.join()
    sftp_thread.join()